﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DarazSdk
{
    /// <summary>
    /// 根据RFC3986协议编码
    /// </summary>
    public class RFC3986Encode
    {
        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string UrlDecode(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            StringBuilder newStr = new StringBuilder();

            foreach (var item in input)
            {
                if (IsReverseChar(item))
                {
                    newStr.Append("%");
                    var temp = ((int)item).ToString("X2");
                    newStr.Append(temp);
                }
                else
                    newStr.Append(item);
            }

            return newStr.ToString();
        }

        /// <summary>
        /// UrlEncode 编码
        /// </summary>
        /// <param name="strSrc"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string UrlEncode(string strSrc)
        {
            StringBuilder sb = new StringBuilder();
            var urf8Bytes = Encoding.UTF8.GetBytes(strSrc);
            foreach (var item in urf8Bytes)
            {
                if (IsReverseChar((char)item))
                {
                    sb.Append('%');
                    sb.Append(ByteToHex(item));
                }
                else
                    sb.Append((char)item);
            }

            return sb.ToString();
        }

        public static string UrlEncode(byte[] strSrc, System.Text.Encoding encoding)
        {
            StringBuilder sb = new StringBuilder();
            var urf8Bytes = strSrc;
            foreach (var item in urf8Bytes)
            {
                if (IsReverseChar((char)item))
                {
                    sb.Append('%');
                    sb.Append(ByteToHex(item));
                }
                else
                    sb.Append((char)item);
            }

            return sb.ToString();
        }

        private static string ByteToHex(byte b)
        {
            return b.ToString("x2").ToUpper();
        }

        private static bool IsReverseChar(char c)
        {
            return !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
                    || c == '-' || c == '_' || c == '.' || c == '~');
        }
    }
}
